<?php

namespace app\admin\controller;


use app\common\model\AppDownloadModel;
use think\facade\Cache;
use think\facade\Request;

class AppdownloadController extends BaseController
{

    public function index()
    {
        $source = Request::param("source");
        $this->assign('source', $source);
        return $this->fetch();
    }

    public function getlist()
    {
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        $device_id  = Request::param("device_id");
        $source     = Request::param("source");

        $page  = Request::param("page");
        $limit = Request::param("limit");

        $where = [];

        if ($source) {
            $where[] = ['source', '=', $source];
        }
        if ($device_id) {
            $where[] = ['device_id', 'like', "%{$device_id}%"];
        }
        if ($start_time) {
            $where[] = ['time', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['time', '<=', $end_time];
        }
        $list = AppDownloadModel::where($where)->page($page, $limit)->order('id', 'desc')->select();
        if (count($list) > 0) {
            $count = AppDownloadModel::where($where)->count();
            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function reset() {
        $device_id = Request::param('device_id');
        if (!$device_id) {
            return self::bulidFail('参数错误');
        }
        // 查询符合条件的多条记录
        $appdownloads = AppDownloadModel::where('device_id', $device_id)
            ->order('duration', 'desc')
            ->order('id', 'desc')
            ->select();
    
        // 检查是否有记录
        if ($appdownloads->isEmpty()) {
            return self::bulidFail('未查询到相关记录');
        }
    
        // 遍历记录并更新 duration 字段为 0
        foreach ($appdownloads as $appdownload) {
            $appdownload->duration = 0;
            $appdownload->save(); // 保存更新后的记录
        }
        Cache::store('redis')->handler()->hdel('live_watch_device', $device_id);
        Cache::store('redis')->handler()->hdel('live_watch_update_list', $device_id);
        // 记录日志
        $log_content = "清零观看时长：" . implode(",", $appdownloads->column('id')) . "，设备id：{$device_id}";
        parent::addAdminLog($log_content);
    
        return self::bulidSuccess();
    }
}